package com.bishe.app.modules.userSaleIncome.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bishe.app.core.common.BizException;
import com.bishe.app.core.enums.IsDel;
import com.bishe.app.modules.groupDaySaleCount.entity.GroupDaySaleCount;
import com.bishe.app.modules.groupDaySaleCount.model.GroupDayCount;
import com.bishe.app.modules.groupDaySaleCount.service.GroupDaySaleCountService;
import com.bishe.app.modules.groupuser.entity.GroupUser;
import com.bishe.app.modules.groupuser.enums.GroupUserPosition;
import com.bishe.app.modules.groupuser.service.impl.GroupUserServiceImpl;
import com.bishe.app.modules.userSaleIncome.entity.UserSaleIncome;
import com.bishe.app.modules.userSaleIncome.mapper.UserSaleIncomeMapper;
import com.bishe.app.modules.userSaleIncome.model.UserSaleIncomeDetailModel;
import com.bishe.app.modules.userSaleIncome.service.UserSaleIncomeService;
import com.bishe.app.modules.usersaledetail.entity.UserSaleDetail;
import com.bishe.app.modules.usersaledetail.model.UserShopSaleItem;
import com.bishe.app.modules.usersaledetail.service.impl.UserSaleDetailServiceImpl;
import kotlin.Triple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * <p>
 * 用户当月提成信息 服务实现类
 * </p>
 *
 * @author
 * @since 2024-03-31
 */
@Service
@Slf4j
public class UserSaleIncomeServiceImpl extends ServiceImpl<UserSaleIncomeMapper, UserSaleIncome> implements UserSaleIncomeService {

    @Resource
    private GroupUserServiceImpl groupUserService;

    @Resource
    private UserSaleDetailServiceImpl saleDetailService;

    @Resource
    private GroupDaySaleCountService groupDaySaleCountService;


    public UserSaleIncome getUserIncome(Long groupId, Long userId, Integer year, Integer mon) {
        return lambdaQuery()
                .eq(UserSaleIncome::getUserId, userId)
                .eq(UserSaleIncome::getGroupId, groupId)
                .eq(UserSaleIncome::getYear, year)
                .eq(UserSaleIncome::getMon, mon)
                .eq(UserSaleIncome::getIsDel, IsDel.N.getCode())
                .one();
    }


    // 计算业绩
    // 计算用户业绩
    @Transactional(rollbackFor = Exception.class)
    public void calcIncome(Long groupId, Long userId, Integer year, Integer mon) {
        // 获取group的销售明细
        GroupUser groupUser = groupUserService.listNonDel(groupId, userId);

        List<UserSaleDetail> userSaleDetails = saleDetailService.listDetailList(userId, year, mon);

//        List<GroupDaySaleCount> list = groupDaySaleCountService.lambdaQuery()
//                .eq(GroupDaySaleCount::getGroupId, groupId)
//                .eq(GroupDaySaleCount::getYear, year)
//                .eq(GroupDaySaleCount::getMon, mon)
//                .eq(GroupDaySaleCount::getIsDel, IsDel.N.getCode())
//                .list();

        // 职位
        Integer position = groupUser.getLeader();

        // shop leader
        Triple<Double, Double, Double> ticheng = null;
        Double singleTicheng = new Double(0.0);
        if (position.equals(GroupUserPosition.LEADER.getCode())) {
            Double total = calcUserSaleTotal(userSaleDetails);
            // AB 班加入店长的收入
//            Integer total =calcGroupCountToLeader(list);
            ticheng = calcShopLeader(total);
        } else if (position.equals(GroupUserPosition.EMPLOYEE.getCode())) {
            Double total = calcUserSaleTotal(userSaleDetails);
            // 非店长/2
            total = total / 2;
            ticheng = calcEmployee(total);
        } else if (position.equals(GroupUserPosition.DU_DAO.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            // 0.3%
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.3")).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.ZONG_JIAN.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            // 0.35%
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.2")).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.CHEN_LIE_SHI.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            // 0.25%
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.3")).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.CAI_GOU.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            // 0.5%
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.8")).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        }  else if (position.equals(GroupUserPosition.CAIWU_ZONGJIAN.getCode())) {
            Double total = calcJianshuTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("1")).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.KUAI_JI.getCode())) {
            Double total = calcJianshuTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.8")).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.SHOU_HUO_YUAN.getCode())) {
            Double total = calcJianshuTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("1")).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.HOU_QIN_ZONG_GUAN.getCode())) {
            Double total = calcJianshuTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("1.8")).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.LI_HUO_YUAN_LIHUO.getCode())) {
            Double total = calcJianshuTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.5")).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.LI_HUO_YUAN_CHEBIAO.getCode())) {
            Double total = calcJianshuTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.6")).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.SONG_HUO_SIJI.getCode())) {
            Double total = calcJianshuTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.4")).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.HR.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.3")).divide(new BigDecimal(100), RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.CHU_NA.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.3")).divide(new BigDecimal(100), RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.SHICHANG_JINGLI.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.6")).divide(new BigDecimal(100), RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.ZONG_JING_LI.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("1")).divide(new BigDecimal(100), RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        } else if (position.equals(GroupUserPosition.ZONG_JING_LI_ZHU_LI.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            Double ticheng1 = new BigDecimal(total).multiply(new BigDecimal("0.4")).divide(new BigDecimal(100), RoundingMode.HALF_UP).doubleValue();
            ticheng = new Triple<>(ticheng1, 0d, 0d);
        }
        else if (position.equals(GroupUserPosition.XIEDIAN_LEADER.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            ticheng = calcShoeLeader(total);

            Double singleTotal = calcSingleYejiTotal(userSaleDetails);
            singleTicheng = new BigDecimal(singleTotal).multiply(new BigDecimal("5")).divide(new BigDecimal(100), RoundingMode.HALF_UP).doubleValue();
        }
        else if (position.equals(GroupUserPosition.XIEDIAN_EMPLOYEE.getCode())) {
            Double total = calcYejiTotal(userSaleDetails);
            total = total/2;
            ticheng = calcShoeEmployee(total);

            Double singleTotal = calcSingleYejiTotal(userSaleDetails);
            singleTicheng = new BigDecimal(singleTotal).multiply(new BigDecimal("5")).divide(new BigDecimal(100), RoundingMode.HALF_UP).doubleValue();
        }
        else {
            throw new BizException("不支持的职位!");
        }

        log.info("当前groupId:{},userId:{},提成:{}", groupId, userId, ticheng);

        // 计算之后落DB
        // 先查询出来
        UserSaleIncome userIncome = getUserIncome(groupId,userId, year, mon);
        UserSaleIncomeDetailModel userSaleIncomeDetailModel = null;
        if (userIncome == null) {
            userIncome = new UserSaleIncome();
            userSaleIncomeDetailModel = UserSaleIncomeDetailModel.init();
        } else {
            userSaleIncomeDetailModel = JSON.parseObject(userIncome.getSaleItem(), UserSaleIncomeDetailModel.class);
        }

        userSaleIncomeDetailModel.setTicheng1(new BigDecimal(String.valueOf(ticheng.getFirst())).divide(new BigDecimal(1), 2, RoundingMode.HALF_UP).toString());
        userSaleIncomeDetailModel.setTicheng2(new BigDecimal(String.valueOf(ticheng.getSecond())).divide(new BigDecimal(1), 2, RoundingMode.HALF_UP).toString());
        userSaleIncomeDetailModel.setTicheng3(new BigDecimal(String.valueOf(ticheng.getThird())).divide(new BigDecimal(1), 2, RoundingMode.HALF_UP).toString());
        userSaleIncomeDetailModel.setSingleTicheng(new BigDecimal(String.valueOf(singleTicheng)).divide(new BigDecimal(1), 2, RoundingMode.HALF_UP).toString());

        userIncome.setGroupId(groupId);
        userIncome.setUserId(userId);
        userIncome.setYear(year);
        userIncome.setMon(mon);
        userIncome.setSaleItem(JSON.toJSONString(userSaleIncomeDetailModel));
        saveOrUpdate(userIncome);

        reCalcShifagongzi(groupId, userId, year, mon);
    }

    private Double calcJianshuTotal(List<UserSaleDetail> userSaleDetails) {
        if (CollectionUtils.isEmpty(userSaleDetails)) {
            return 0.0;
        }

        Double total = 0.0;
        for (UserSaleDetail userSaleDetail : userSaleDetails) {
            UserShopSaleItem userShopSaleItem = JSON.parseObject(userSaleDetail.getSaleItem(), UserShopSaleItem.class);
            Double yeji = getSaleTotal(userShopSaleItem.getSale());

            total += Optional.ofNullable(yeji).orElse(0.0);
        }

        return total;
    }

    private Double calcYejiTotal(List<UserSaleDetail> userSaleDetails) {

        if (CollectionUtils.isEmpty(userSaleDetails)) {
            return 0.0;
        }

        Double total = 0.0;
        for (UserSaleDetail userSaleDetail : userSaleDetails) {
            UserShopSaleItem userShopSaleItem = JSON.parseObject(userSaleDetail.getSaleItem(), UserShopSaleItem.class);
            Double yeji = getSaleTotal(userShopSaleItem.getSale());

            total += Optional.ofNullable(yeji).orElse(0.0);
        }

        return total;
    }

    /**
     * 单人业绩
     *
     * @param userSaleDetails
     * @return
     */
    private Double calcSingleYejiTotal(List<UserSaleDetail> userSaleDetails) {

        if (CollectionUtils.isEmpty(userSaleDetails)) {
            return 0.0;
        }

        Double total = 0.0;
        for (UserSaleDetail userSaleDetail : userSaleDetails) {
            UserShopSaleItem userShopSaleItem = JSON.parseObject(userSaleDetail.getSaleItem(), UserShopSaleItem.class);
            Double yeji = getSaleTotal(userShopSaleItem.getSaleSingle());

            total += Optional.ofNullable(yeji).orElse(0.0);
        }

        return total;
    }

    private Triple<Double, Double, Double> calcEmployee(Double total) {
        total = total;
        // 5.5w元以下
        Double result1 = 0.0;
        Double result2 = 0.0;
        Double result3 = 0.0;
        if (total < 55000) {
            result1 = new BigDecimal(total).multiply(BigDecimal.valueOf(2.5)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
        } else if (total < 75000) {
            result1 = new BigDecimal(55000).multiply(BigDecimal.valueOf(2.5)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            result2 = new BigDecimal(total - 55000).multiply(BigDecimal.valueOf(3)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
        } else {
            result1 = new BigDecimal(55000).multiply(BigDecimal.valueOf(2.5)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            result2 = new BigDecimal(75000 - 55000).multiply(BigDecimal.valueOf(3)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            result3 = new BigDecimal(total - 75000).multiply(BigDecimal.valueOf(4)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
        }
        return new Triple<>(result1, result2, result3);
    }

    private Triple<Double, Double, Double> calcShoeEmployee(Double total) {
        total = total;
        // 5.5w元以下
        Double result1 = 0.0;
        Double result2 = 0.0;
        Double result3 = 0.0;
        if (total < 6_0000) {
            result1 = new BigDecimal(total).multiply(BigDecimal.valueOf(3.5)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
        } else if (total < 10_0000) {
            result1 = new BigDecimal(6_0000).multiply(BigDecimal.valueOf(3.5)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            result2 = new BigDecimal(total - 10_0000).multiply(BigDecimal.valueOf(4)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
        } else {
            result1 = new BigDecimal(6_0000).multiply(BigDecimal.valueOf(3.5)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            result2 = new BigDecimal(10_0000 - 6_0000).multiply(BigDecimal.valueOf(4)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
            result3 = new BigDecimal(total - 10_0000).multiply(BigDecimal.valueOf(5)).divide(new BigDecimal(100), 2, RoundingMode.HALF_UP).doubleValue();
        }
        return new Triple<>(result1, result2, result3);
    }

    private Triple<Double, Double, Double> calcShopLeader(Double total) {
        total = total;
        // 5.5w元以下
        Double result1 = 0.0;
        Double result2 = 0.0;
        Double result3 = 0d;
        if (total < 28_0000) {
            result1 = new BigDecimal(total).multiply(BigDecimal.valueOf(1.25)).divide(new BigDecimal(100)).doubleValue();
        } else if (total < 35_0000) {
            result1 = new BigDecimal(28_0000).multiply(BigDecimal.valueOf(1.25)).divide(new BigDecimal(100)).doubleValue();
            result2 = new BigDecimal(total - 28_0000).multiply(BigDecimal.valueOf(1.5)).divide(new BigDecimal(100)).doubleValue();
        } else {
            result1 = new BigDecimal(28_0000).multiply(BigDecimal.valueOf(1.25)).divide(new BigDecimal(100)).doubleValue();
            result2 = new BigDecimal(35_0000 - 28_0000).multiply(BigDecimal.valueOf(1.5)).divide(new BigDecimal(100)).doubleValue();
            result3 = new BigDecimal(total - 35_0000).multiply(BigDecimal.valueOf(2)).divide(new BigDecimal(100)).doubleValue();
        }
        return new Triple<>(result1, result2, result3);
    }

    private Triple<Double, Double, Double> calcShoeLeader(Double total) {
        total = total;
        // 5.5w元以下
        Double result1 = 0.0;
        Double result2 = 0.0;
        Double result3 = 0d;
        if (total < 18_0000) {
            result1 = new BigDecimal(total).multiply(BigDecimal.valueOf(1.75)).divide(new BigDecimal(100)).doubleValue();
        } else if (total < 25_0000) {
            result1 = new BigDecimal(18_0000).multiply(BigDecimal.valueOf(1.75)).divide(new BigDecimal(100)).doubleValue();
            result2 = new BigDecimal(total - 18_0000).multiply(BigDecimal.valueOf(2.0)).divide(new BigDecimal(100)).doubleValue();
        } else {
            result1 = new BigDecimal(18_0000).multiply(BigDecimal.valueOf(1.75)).divide(new BigDecimal(100)).doubleValue();
            result2 = new BigDecimal(25_0000 - 18_0000).multiply(BigDecimal.valueOf(2.0)).divide(new BigDecimal(100)).doubleValue();
            result3 = new BigDecimal(total - 25_0000).multiply(BigDecimal.valueOf(2.5)).divide(new BigDecimal(100)).doubleValue();
        }
        return new Triple<>(result1, result2, result3);
    }

    private Double calcUserSaleTotal(List<UserSaleDetail> list) {
        if (CollectionUtils.isEmpty(list)) {
            return 0.0;
        }

        Double total = 0.0;
        for (UserSaleDetail userSaleDetail : list) {
            String saleItem = userSaleDetail.getSaleItem();
            UserShopSaleItem userShopSaleItem = JSON.parseObject(saleItem, UserShopSaleItem.class);

            total += getSaleTotal(userShopSaleItem.getSale());
        }
        return total;
    }

    public Double getSaleTotal(String saleExpr) {
        if (StringUtils.isEmpty(saleExpr)) {
            return 0.0;
        }
        return calculate(saleExpr);
    }

    private static ExpressionParser parser = new SpelExpressionParser();

    public static Double calculate(String expression) {
        Expression parseExpression = parser.parseExpression(expression);
        return Double.valueOf(parseExpression.getValue().toString());
    }


    @Override
    public void reCalcShifagongzi(Long groupId, Long userId, Integer year, Integer mon) {
        UserSaleIncome userIncome = getUserIncome(groupId, userId, year, mon);
        String saleItem = userIncome.getSaleItem();
        UserSaleIncomeDetailModel userSaleIncomeDetailModel = JSON.parseObject(saleItem, UserSaleIncomeDetailModel.class);
        userSaleIncomeDetailModel.reCalcShifagongzi();

        lambdaUpdate()
                .set(UserSaleIncome::getSaleItem, JSON.toJSONString(userSaleIncomeDetailModel))
                .eq(UserSaleIncome::getId, userIncome.getId())
                .update();
    }
}
